import { ref, reactive, watch, inject } from 'vue'
import { PLAY_STATE } from '../models/status';
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'

export default ({ el }) => {
    const api = inject('api')
    const route = useRoute()
    const store = useStore()

    const player = ref(null)
    const playerParams = reactive({
        playState: PLAY_STATE.NOT_STARTED,
        isPlaying: false,
        // 是否允许播放
        allowPlay: false,
        // 当前播放时间
        currentTime: 0
    })
    const data = reactive({
        url: '',
        poster: '',
        ajaxTimer: null
    })

    
    // 初始化 player
    const initPlayer = () => {
        console.log(el)
        player.value = TCPlayer(el, {
            controls: true,
            autoplay: playerParams.playState === PLAY_STATE.PLAYING,
            poster: data.poster
        });
        player.value.src(data.url);
        playerListener();
    }
    // 销毁播放器
    function destroyPlayer () {
        if (player.value) {
            player.value.dispose();
            player.value = null
            document.getElementById(`#${el}`).innerHTML = ''
        }
    }
    // 播放监听
    const playerListener = () => {
        // 暂停时触发。
        player.value.on('pause', eventPause);
        // 因缓冲而暂停或停止后恢复播放时触发，paused 属性为 false 。通常用这个事件来标记视频真正播放，play 事件只是开始播放，画面并没有开始渲染。
        player.value.on('playing', eventPlaying);
        // 播放停止，下一帧内容不可用时触发。
        player.value.on('waiting', eventWaiting);
        // 当播放器能够开始播放视频时触发。
        player.value.on('canplay', eventCanplay);
        // 视频播放已结束时触发。此时 currentTime 值等于媒体资源最大值。
        player.value.on('ended', eventEnded);
        // 视频播放出现错误时触发
        player.value.on('error', eventError);
    }

    function eventPause () {
        console.log('=== 暂停 ===')
        playerParams.playState = PLAY_STATE.PAUSED;
        playerParams.isPlaying = false
        playerParams.allowPlay = true;
    }

    function eventPlaying () {
        console.log('=== 真正的开始播放 ===')
        playerParams.playState = PLAY_STATE.PLAYING;
        playerParams.isPlaying = true
        playerParams.allowPlay = false;
    }

    function eventWaiting () {
        console.log('=== 播放停止，下一帧内容不可用时触发 ===')
        playerParams.playState = PLAY_STATE.PAUSED;
        playerParams.isPlaying = false
        playerParams.allowPlay = true;
    }

    function eventCanplay () {
        console.log('=== 当播放器能够开始播放视频时触发 ===')
        playerParams.playState = PLAY_STATE.PAUSED;
        playerParams.isPlaying = false
        playerParams.allowPlay = true;
    }

    function eventEnded () {
        playerParams.playState = PLAY_STATE.ENDED;
        playerParams.isPlaying = false;
        playerParams.allowPlay = false;
        console.log('=== 视频播放已结束 ===')
    }

    function eventError () {
        playerParams.isPlaying = false;
        playerParams.allowPlay = false;
        console.log('=== 视频播放出现错误 ===')
    }

    function ajaxPlayerStatus_200 () {
        if (!player.value) {
            initPlayer();
            player.value.play();
        }
        playerParams.allowPlay = true;

    }
    function ajaxPlayerStatus_404 () {
        if (player.value) {
            player.value.pause();
        }
        playerParams.allowPlay = false;
    }
    function getPushPlayerHandle (status) {
        switch (status) {
            case 200:
                ajaxPlayerStatus_200();
                break;
            case 404:
                ajaxPlayerStatus_404();
                break;
        }
    }

    // 心跳借口
    function apiHeartbeat () {
        if (!window.localStorage.hasOwnProperty('openid')) return
        if (!route.params.id) return

        const openid = window.localStorage.getItem('openid')

        let type = 0
        switch (playerParams.playState) {
            case PLAY_STATE.NOT_STARTED:
                type = 1
                break
            case PLAY_STATE.PLAYING:
                type = playerParams.isPlaying ? 22 : 21
                break
            case PLAY_STATE.ENDED:
                type = 3
                break
            case PLAY_STATE.PLAY_BACK:
                type = playerParams.isPlaying ? 41 : 42
                break
        }
        void api.watchHeartbeat({
            // contentJson: window.navigator.userAgent,
            liveId: route.params.id,
            type,
            auid: openid
        })
    }

    // 节流心跳
    function throttleHeartbeat(interval = 3 * 1000) {
        let lastTime = 0
        const _throttle = function () {
            const nowTime = new Date().getTime()
            const remainTime = nowTime - lastTime
            if (remainTime - interval >= 0) {
                apiHeartbeat()
                lastTime = nowTime
            }
        }
        // 返回_throttle函数
        return _throttle
    }

    // 计算推流状态
    let ajax = null
    function getPushPlayer () {
        if (!ajax) ajax = new XMLHttpRequest();
        ajax.open('get', data.url);
        ajax.send();
        ajax.onreadystatechange = () => {
            if (ajax.readyState == 4) {
                getPushPlayerHandle(ajax.status);
                // 心跳节流
                // throttleHeartbeat();
                console.log('ajaxStatus ===>', ajax.status)
                if (data.ajaxTimer) {
                    clearTimeout(data.ajaxTimer)
                    data.ajaxTimer = null
                }
                data.ajaxTimer = setTimeout(getPushPlayer, 1000)
            }
        }
    }

    // 获取完毕详情之后，开始
    watch(() => store.state.live.detail, newVal => {
        // 当ajax有值的时候，就不需要触发了
        if (newVal.id === route.params.id && !ajax) {
            data.url = store.state.live.detail.pullStreamUrl
            data.poster = `//${store.state.live.detail.previewPicture}`

            playerParams.playState = PLAY_STATE.NOT_STARTED
            playerParams.isPlaying = false
            playerParams.allowPlay = false
            playerParams.currentTime = 0

            getPushPlayer()
        }
    })

    return {
        player,
        playerParams,
        data,
        apiHeartbeat
    }
}
